package redislock

import (
	"fmt"
	"time"

	"gitee.com/zawei/yggdrasil/pkg/config"
	"gitee.com/zawei/yggdrasil/pkg/lib/redis"
	"gitee.com/zawei/yggdrasil/pkg/log"
	"github.com/google/uuid"
)

const (
	defaultTTL        = time.Second * 5
	defaultMinBackoff = time.Millisecond * 50
	defaultMaxBackoff = time.Millisecond * 500
)

func defaultUUIDGen() string {
	return uuid.Must(uuid.NewUUID()).String()
}

type Config struct {
	Redis *redis.Config

	TTL        time.Duration
	MinBackoff time.Duration
	MaxBackoff time.Duration

	uuidGen func() string
}

func StdConfig(name string) *Config {
	return RawConfig(fmt.Sprintf("redislock.%s", name))
}

func RawConfig(key string) *Config {
	c := new(Config)
	if err := config.Get(key).Scan(c); err != nil {
		log.Fatalw("fault to scan redislock config", "error", err)
	}
	return c
}

func (c *Config) WithUuidGen(f func() string) *Config {
	c.uuidGen = f
	return c
}

//Build
func (c *Config) Build() *RedisLocker {
	if c.TTL == 0 {
		c.TTL = defaultTTL
	}
	if c.MinBackoff == 0 {
		c.MinBackoff = defaultMinBackoff
	}
	if c.MaxBackoff == 0 {
		c.MaxBackoff = defaultMaxBackoff
	}
	return newRedisLocker(c)
}
